package com.only4play.mybatis.support;

import com.only4play.common.model.ValidateResult;
import com.only4play.common.validator.ValidateGroup;
import org.springframework.util.CollectionUtils;

import jakarta.validation.*;
import jakarta.validation.groups.Default;
import java.util.List;
import java.util.Set;

/**
 * 实体操作基础父类
 *
 * @author liyuncong
 * @date 2023/11/07 09:27
 **/
public abstract class BaseEntityOperation implements EntityOperation {
    static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public <T> void doValidate(T t, Class<? extends ValidateGroup> group) {
        Set<ConstraintViolation<T>> constraintViolations = validatorFactory.getValidator().validate(t, group, Default.class);
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            List<ValidateResult> results = constraintViolations.stream()
                    .map(cv -> new ValidateResult(cv.getPropertyPath().toString(), cv.getMessage()))
                    .toList();
            // TODO
            throw new ValidationException(String.valueOf(results));
        }
    }
}
